<template>
  <el-dialog
  :title="formTitle"
  v-model="formData.visible"
  width="60%"
  :before-close="handleClose">
<el-form ref="form" label-width="120px">
  <el-divider content-position="left">基本信息</el-divider>
    <el-form-item label="商品名称">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
      <el-form-item label="分类">
      <el-cascader filterable placeholder="输入文字进行搜索" style="width:100%;"
      :options="formData.forms[1].Options"
      :props="{children: 'ChildRen', value: 'Value', label:'Label', multiple:true}"
      collapse-tags
      v-model="data"
      ></el-cascader>
    </el-form-item>
    <!-- 单图上传 -->
    <el-form-item label="商品图片" @click="SelectImages(true,1)">
      <template  v-if="data.Image != undefined && data.Image.length != 0" >
        <el-image
          v-for="imgItems in data.Image" :key="imgItems.FileId"
          :src="BASE_IMAGE_URL + imgItems.FileName"
          class="avatar">
        </el-image>
      </template>
      <i v-else
      @click="SelectImages(true,1)"
      class="el-icon-plus avatar-uploader-icon"
      style="border:solid 1px #ccc;font-size:30px;padding:48px;">
      </i>
    </el-form-item>
    <el-form-item label="商品卖点">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
  <el-divider content-position="left">规格/库存</el-divider>
    <el-form-item label="商品规格">
        <el-radio v-model="data.SpecType" label="10">单规格</el-radio>
        <el-radio v-model="data.SpecType" label="20">多规格</el-radio>
    </el-form-item>
    <template v-if="data.SpecType == 10">
    <el-form-item label="商品编码">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
    <el-form-item label="商品价格">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
    <el-form-item label="商品划线价">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
    <el-form-item label="当前库存数量 ">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
    <el-form-item label="商品重量(Kg)">
      <el-input  v-model="data.ProductName" clearable></el-input>
    </el-form-item>
    </template>
    <template v-if="data.SpecType == 20">
      <div style="border:1px solid #ccc;border-radius: 2px;padding:10px;text-align:left;margin-left:120px;margin-bottom:20px" v-if="ShowSpec">
        <el-form-item label="规格名">
          <el-input  v-model="data.ProductName" clearable></el-input>
        </el-form-item>
        <el-form-item label="规格值">
          <el-input  v-model="data.ProductName" clearable></el-input>
        </el-form-item>
        <el-button style="margin-left:60px" type="primary" size="mini" plain>确定</el-button>
        <el-button plain size="mini" @click="ShowSpec = false">取消</el-button>
      </div>
      <div  v-for="(first,firstIndex) in Product" :key="firstIndex" style="border:1px solid #ccc;border-radius: 2px;padding:10px;text-align:left;margin-left:120px;margin-bottom:20px">
          <el-input style="width:100px" v-model="first.value" clearable></el-input> :
          <el-checkbox v-model="second.checked" v-for="(second,secondIndex) in first.spec" :key="secondIndex">
            <el-input style="width:140px" v-model="second[secondIndex]" clearable></el-input>
          </el-checkbox>
          <!-- <i class="el-icon-minus operate"></i> -->
          <i class="el-icon-plus operate" @click="addSkuSpec(first,firstIndex)"></i>
          <!-- <el-button class="operate" type="primary" size="mini" plain>确定</el-button> -->
      </div>
      <br/>
      <div style="border:1px solid #ccc;border-radius: 2px;padding:10px;text-align:left;margin-left:120px">
        <el-button @click="addSpec()" size="mini" type="primary" plain>添加规格</el-button>
        <el-button @click="addSku()" size="mini" type="primary" plain>添加SKU</el-button>
      </div>
    <div style="border:1px solid #ccc;border-radius: 2px;padding:10px;text-align:left;margin-left:120px;margin-top:10px;">
      <el-table
        :data="table.tableData"
        :span-method="arraySpanMethod"
        show-overflow-tooltip=true
        border
        style="width: 100%">
        <el-table-column
        v-for="(item_column,index) in table.tableColumn"
        :row-key="item_column"
        :key="index"
        :prop="item_column" :label="item_column">
        <template #default="scope" v-if="item_column == '图片'">
          <el-image
          style="width: 50px; height: 50px"
          hide-on-click-modal=true
          fit="fit"></el-image>
        </template>
        <template #default="scope" v-else-if="item_column == '销售价' || item_column ==  '划线价' || item_column == '库存' || item_column == '重量(kg)' ">
          <el-input  v-model="data.ProductName" clearable></el-input>
        </template>
        </el-table-column>
      </el-table>
    </div>
    </template>
    <el-form-item label="库存计算方式">
      <el-radio v-model="data.SpecType" label="10">下单减库存</el-radio>
        <el-radio v-model="data.SpecType" label="20">付款减库存</el-radio>
    </el-form-item>
  <el-divider content-position="left">商品详情</el-divider>
    <!-- Markdown富文本编辑器 -->
    <el-form-item label="商品详情">
      <!-- {{formItem.Key}} -->
      <MarkDownEditor
      :Content="data.Content"
      @SaveMarkDown="SaveMarkDown"
      />
    </el-form-item>
  <el-divider content-position="left">其他设置</el-divider>

    <el-form-item label="运费模版">
    <el-select v-model="value" placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
    </el-form-item>
    <el-form-item label="商品状态">
        <el-radio v-model="data.SpecType" label="10">上架</el-radio>
        <el-radio v-model="data.SpecType" label="20">下架</el-radio>
    </el-form-item>
    <el-form-item label="初始销量">
      <el-input  v-model="data.ProductSales" clearable></el-input>
    </el-form-item>
    <el-form-item label="商品排序">
      <el-input  v-model="data.ProductSort" clearable></el-input>
    </el-form-item>
  <el-divider content-position="left">积分设置</el-divider>
    <el-form-item label="开启积分赠送">
      <el-radio v-model="data.SpecType" label="10">开启</el-radio>
      <el-radio v-model="data.SpecType" label="20">关闭</el-radio>
    </el-form-item>
    <el-form-item label="使用积分抵扣">
      <el-radio v-model="data.SpecType" label="10">允许</el-radio>
      <el-radio v-model="data.SpecType" label="20">不允许</el-radio>
    </el-form-item>
  <el-divider content-position="left">会员折扣设置</el-divider>
    <el-form-item label="开启会员折扣">
      <el-radio v-model="data.SpecType" label="10">开启</el-radio>
      <el-radio v-model="data.SpecType" label="20">关闭</el-radio>
    </el-form-item>
    <el-form-item label="会员折扣设置">
        <el-radio v-model="data.SpecType" label="10">默认折扣</el-radio>
      <el-radio v-model="data.SpecType" label="20">单独设置</el-radio>
    </el-form-item>
  <el-divider content-position="left">分销设置</el-divider>
      <el-form-item label="开启单独分销">
        <el-radio v-model="data.SpecType" label="10">开启</el-radio>
        <el-radio v-model="data.SpecType" label="20">关闭</el-radio>
    </el-form-item>
</el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleOk">确 定</el-button>
    </span>
  </template>
</el-dialog>
<UploadDialog
:UploadDialogVisible="UploadDialogVisible"
:CheckLimit="CheckLimit"
:Checked="Checked"
@SaveUploadFile="SaveUploadFile"
@CancelUploadFile="CancelUploadFile"
/>
</template>
<script>
import MarkDownEditor from '@/components/editor/markdown/index'
import { reactive, ref } from 'vue';
import UploadDialog from '../upload/upload-file-dialog';
import { BASE_IMAGE_URL } from '../../utils/config';
export default {
  name:"ProductDialog",
    components: {
    MarkDownEditor,
    UploadDialog
  },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    formData:{
      type: Object,
      default: () => {}
    },
  },
  setup(props, { emit }) {
    let options = [{
          value: '1',
          label: '全国'
        }, {
          value: '2',
          label: '广东'
        }]
    let table = reactive({
      tableData: [],
      tableColumn: [],
      firstColumnRule:[]
    })
    let Product = reactive(
      [
        {value:"颜色",spec:[{0:"深空灰",checked:false},{1:"银色",checked:false},{2:"香槟金",checked:false}]},
        {value:"内存",spec:[{0:"128g",checked:false},{1:"256g",checked:false},{2:"512g",checked:false}]},
        {value:"型号",spec:[{0:"MacBook Air",checked:false},{1:"MacBook Pro",checked:false}]}
      ])
    let SpecVisible = ref(false)
    let ShowSpec = ref(false)
    let SelectArr = []
    let first_column_rule = []
    let Checked = Array.isArray(props.Checked)?props.Checked:reactive([])
    let CheckLimit = ref(1)
    let UploadDialogVisible = ref(false)
    function isImage(FileName){
      let IMAGE = BASE_IMAGE_URL + FileName
      return IMAGE
    }
    // 选择图片
    function SelectImages(Visible,Limit)
    {
      UploadDialogVisible.value = Visible
      CheckLimit.value = Limit
    }
    // 图库选择的完毕
    function SaveUploadFile(){
      UploadDialogVisible.value = false
      if(CheckLimit == 1){
        props.data.Image = Checked[0]
      }else
      {
        props.data.Image = Checked
      }
    }
    // 图库关闭
    function CancelUploadFile(){
      UploadDialogVisible.value = false
    }
    // 添加规格
    function addSpec(){
      ShowSpec = true
      Product.push({value:"",spec:[]});
    }
    // 添加规格子项
    function addSkuSpec(data){
      data.spec.push({checked:false})
    }

    // 添加SKU
    function addSku(){
      let arr = []
      Product.forEach(first => {
        // arr.push({first.value})
        let result = []
        // result.push(first.value)
        for (let i = 0; i <  first.spec.length; i++) {
          if(first.spec[i].checked)
          {
            if(first.spec[i][i] != '')
            {
              result.push(first.spec[i][i])
            }
          }
        }
        if(result.length != 0)
        {
          arr.push({"attr":first.value,"valueList":result})
        }
        // console.log(tableColumn)
      });
      if(arr.length > 0)
      {
        table.tableData = generateBaseData(arr).map(item => ({ ...item, '图片': '', '销售价': '', '划线价': '', '库存': '', '重量(kg)':''}))
        table.tableColumn = arr.map(x => x.attr).concat(['图片', '销售价', '划线价', '库存', '重量(kg)'])
        console.log(table.tableData)
      }
    }
    // 合并行
    function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex == 0) {
            let key_0 = column.label
            let first_idx = table.tableData.findIndex(x => x[key_0] == row[key_0])
            const calcSameLength = () => table.tableData.filter(x => x[key_0] == row[key_0]).length
            first_column_rule = rowIndex == first_idx ? [calcSameLength(), 1] : [0, 0]
            return first_column_rule
        // //     // 第二列的图片与第一列主规格使用相同合并规则 ( 恰好el-table的合并方法是横着走的 )
        // } else if (columnIndex == 1) {
        //     return first_column_rule
        //     // 其他列
        } else {
            // 表格数据的每一项,
            const callBacks = (table_item, start_idx = 0) => {
                if (columnIndex < start_idx) return true
                let curr_key = table.tableColumn[start_idx]
                return table_item[curr_key] === row[curr_key] && callBacks(table_item, ++start_idx)
            }
            let first_idx = table.tableData.findIndex(x => callBacks(x))
            const calcSameLength = () => table.tableData.filter(x => callBacks(x)).length
            return rowIndex == first_idx ? [calcSameLength(), 1] : [0, 0]
        }
    }
  function generateBaseData(arr) {
    if (arr.length === 0) return []
    if (arr.length === 1) {
        let [item_spec] = arr
        return item_spec.valueList.map(x => {
            return {
                [item_spec.attr]: x
            }
        })
    }
    if (arr.length >= 1) {
        return arr.reduce((accumulator, spec_item) => {
            let acc_value_list = Array.isArray(accumulator.valueList) ? accumulator.valueList : accumulator
            let item_value_list = spec_item.valueList
            let result = []
            for (let i in acc_value_list) {
                for (let j in item_value_list) {
                    let temp_data = {}
                    // 如果是对象
                    if (acc_value_list[i].constructor === Object) {
                        temp_data = {
                            ...acc_value_list[i],
                            [spec_item.attr]: item_value_list[j]
                        }

                        // 否则如果是字符串
                    } else {
                        temp_data[accumulator.attr] = acc_value_list[i]
                        temp_data[spec_item.attr] = item_value_list[j]
                    }
                    result.push(temp_data)
                }
            }
            return result
        })
      }
    }
    return {
      table,
      generateBaseData,
      arraySpanMethod,
      addSku,
      addSpec,
      addSkuSpec,
      SelectArr,
      Checked,
      BASE_IMAGE_URL,
      SaveUploadFile,
      CancelUploadFile,
      UploadDialogVisible,
      CheckLimit,
      SelectImages,
      options,
      SpecVisible,
      ShowSpec,
      Product
    };
  }
}
</script>
<style lang="postcss" scoped>
.avatar{
  width: 140px;
  height: 140px;
  margin:0 5px;
}
.el-popper__arrow{
  display: none !important;
}
.el-divider >>> div{
  font-weight: bold !important;
  border-left: 5px solid #409EFF;
  left: 0;
  padding-left: 4px;
  font-size: 16px;
}
.el-form-item >>> .el-form-item__content{
  text-align: left;
  padding-left: 30px;
}
.operate{
  margin-left: 5px;
  padding: 10px;
  border-radius: 5px;
  border: solid 1px #ccc;
  background: #dfefff;
  color: #409EFF;
}
.operate:hover{
  background: #409EFF;
  cursor: pointer;
  color: white;
}
</style>
